import { appContext } from "@/models/app.context";
import { appRef } from "@/models/app.ref";
import { SexType, UserInfo } from "@/models/user";
import router from "@/router";
import { MessagePlugin } from "tdesign-vue-next";
import { BaseServices } from "./base.services";
import { APIUrl, APIMethod, RespInfo } from "./request.services";
import { Md5 } from 'ts-md5';


class UserService extends BaseServices {
  private static _ins: UserService = new UserService();
  public static get ins(): UserService {
    return this._ins ? this._ins : this._ins = new UserService();
  }

  /** 登录 */
  public login(email: string, password: string): Promise<void> {
    const url = APIUrl.User + APIMethod.Login;
    const data = { email, password: Md5.hashStr(password) };
    return new Promise<void>((reslove, reject) => {
      this.request(url, data).then(async (res: any) => {
        appContext.setGlobal({ token: res.token });
        MessagePlugin("success", "登录成功");
        await this.getUserByInfo();
        router.replace("/")
        reslove();
      }).catch(err => {
        reject(err)
      });
    });
  }

  /** 获取用户信息 */
  public getUserByInfo(): Promise<void> {
    const url = APIUrl.User + APIMethod.Token;
    const data = {};
    return new Promise<void>((reslove, reject) => {
      if (!localStorage.getItem('token')) {
        reslove(); return;
      }
      this.request(url, data).then(async (res: any) => {
        appRef.user.setData(res.info)
        reslove();
      }).catch(err => {
        reslove(err)
      });
    });
  }

  /** 退出登录 */
  public loginOut(): void {
    appRef.user.setData({} as UserInfo);
    localStorage.removeItem('token');
    MessagePlugin("success", "退出成功");
    location.reload();
  }


  /** 注册 */
  public register(password: string, code: string, secret: string): Promise<void> {
    const url = APIUrl.User + APIMethod.Register;
    const data = { password: Md5.hashStr(password), code, secret };
    return new Promise<void>((reslove, reject) => {
      this.request(url, data).then(async (res: any) => {
        appContext.setGlobal({ token: res.token });
        MessagePlugin("success", "注册成功");
        await this.getUserByInfo();
        router.replace("/")
        reslove();
      }).catch(err => {
        reslove(err)
      });
    });
  }

  /** 找回密码 */
  public forgotPassword(password: string, code: string, secret: string): Promise<void> {
    const url = APIUrl.User + APIMethod.ForgotPassword;
    const data = { password: Md5.hashStr(password), code, secret };
    return new Promise<void>((reslove, reject) => {
      this.request(url, data).then(async (res: any) => {
        appContext.setGlobal({ token: res.token });
        MessagePlugin("success", "修改成功");
        await this.getUserByInfo();
        router.replace("/")
        reslove();
      }).catch(err => {
        reslove(err)
      });
    });
  }

  /** 修改用户基础信息 */
  public updatedBaseInfo(uid: string, nick: string, birthday: number, motto: string, sex: SexType, name?: string, avatar?: string): Promise<void> {
    const url = APIUrl.User + APIMethod.Updated;
    const data = { uid, avatar, name, nick, birthday, motto, sex };
    return new Promise<void>((reslove, reject) => {
      this.request(url, data).then((res: any) => {
        appRef.user.setData(res.info)
        MessagePlugin("success", "修改成功");
        reslove();
      })
    });
  }
  /** 修改密码 */
  public updatedPassword(uid: string, oldPsw: string, newPsw: string): Promise<void> {
    const url = APIUrl.User + APIMethod.Password;
    const data = { uid, oldpsw: Md5.hashStr(oldPsw), newpsw: Md5.hashStr(newPsw) };
    return new Promise<void>((reslove, reject) => {
      this.request(url, data).then(res => {
        MessagePlugin("success", "修改成功");
        reslove();
      })
    });
  }

  /** 获取所有用户 */
  public list(page: number = 0, number: number = 0): Promise<RespInfo<UserInfo>> {
    const url = APIUrl.User + APIMethod.List;
    const data = { page, number };
    return new Promise<RespInfo<UserInfo>>((reslove, reject) => {
      this.request(url, data).then(async (res: RespInfo<UserInfo>) => {
        reslove(res);
      })
    });
  }


}

export const userService: UserService = UserService.ins;